package controller;

import com.google.gson.Gson;
import entity.ClockInRecord;
import service.ClockService;
import com.alibaba.fastjson.JSON;
import service.impl.ClockServicelmpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/ClockReportController")
public class ClockReportController extends HttpServlet {
    private ClockService clockService = new ClockServicelmpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String op = request.getParameter("op");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false); // 严格模式
        PrintWriter out = response.getWriter();
        
        if ("search".equals(op)) {
            try {
                String startDateStr = request.getParameter("startDate");
                String endDateStr = request.getParameter("endDate");
                
                // 验证参数不为空
                if(startDateStr == null || endDateStr == null || 
                   startDateStr.trim().isEmpty() || endDateStr.trim().isEmpty()) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "开始日期和结束日期不能为空");
                    return;
                }
                
                // 验证日期格式
                if(!startDateStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}") || 
                   !endDateStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "日期格式必须为: yyyy-MM-dd HH:mm:ss");
                    return;
                }
                
                Date startDate = sdf.parse(startDateStr);
                Date endDate = sdf.parse(endDateStr);
                
                // 查询数据库
                List<ClockInRecord> records = clockService.getClockRecords(startDate, endDate);
                out.write(JSON.toJSONString(records));
                
            } catch (ParseException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "日期格式必须为: yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
                e.printStackTrace();
            }
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        doGet(request, response);
    }


    }